<template>
  <div class="inventory-add-container">
    <!-- 基础信息 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">基础信息</span>
        </div>
      </template>

      <el-form :model="formData" label-width="120px" class="add-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="盘点单号" required>
              <el-input v-model="formData.code" placeholder="自动获取系统编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点类型" required>
              <el-select v-model="formData.inventoryTypeId" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="type in inventoryTypeList" :key="type.value" :label="type.label"
                  :value="type.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="盘点开始时间" required>
              <el-date-picker v-model="formData.startTime" type="datetime" placeholder="请选择" style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" @change="handleStartTimeChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点结束时间" required>
              <el-date-picker v-model="formData.endTime" type="datetime" placeholder="请选择" style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" @change="handleEndTimeChange" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" required>
              <div class="input-with-action">
                <el-select v-model="formData.warehouse" placeholder="请选择仓库" style="flex: 1" filterable clearable>
                  <el-option v-for="warehouse in warehouseList" :key="warehouse.value" :label="warehouse.label"
                    :value="warehouse.value" />
                </el-select>
                <el-link type="primary" :underline="false" style="margin-left: 10px" @click="handleWarehouseSetting">
                  设置
                </el-link>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" required>
              <el-input v-model="selectedHandlerName" placeholder="请选择经办人" readonly style="width: 100%">
                <template #suffix>
                  <el-icon style="cursor: pointer;  font-size: 16px" @click="handleOpenHandlerDialog">
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 经办人选择对话框 -->
    <el-dialog v-model="handlerDialogVisible" title="选择经办人" width="1000px" :close-on-click-modal="false"
      @close="handleDialogClose">
      <div class="handler-dialog-content">
        <!-- 左侧：部门选择器 -->
        <div class="dialog-left">
          <el-input v-model="deptSearchKeyword" placeholder="请搜索" clearable style="margin-bottom: 12px">
            <template #suffix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-tree ref="deptTreeRef" :data="deptTreeData" :props="deptTreeProps" node-key="value"
            :highlight-current="true" :expand-on-click-node="false" :filter-node-method="filterDeptNode"
            @node-click="handleDeptNodeClick"
            style="height: 400px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 8px" />
        </div>

        <!-- 中间：经办人列表 -->
        <div class="dialog-center">
          <el-input v-model="handlerSearchKeyword" placeholder="请搜索" clearable style="margin-bottom: 12px">
            <template #suffix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar height="400px" style="border: 1px solid #dcdfe6; border-radius: 4px">
            <div class="handler-list">
              <div v-for="(handler, index) in filteredHandlerList" :key="`handler-${handler.value}-${index}`"
                class="handler-item" :class="{ 'is-selected': isHandlerSelected(handler.value) }"
                @click="toggleHandlerSelection(handler)">
                <el-icon v-if="isHandlerSelected(handler.value)" color="#67c23a" style="margin-right: 8px">
                  <Check />
                </el-icon>
                <span>{{ handler.label }}</span>
                <span style="color: #909399; font-size: 12px; margin-left: 8px">(ID: {{ handler.value }})</span>
              </div>
              <el-empty v-if="filteredHandlerList.length === 0" description="暂无数据" :image-size="100" />
            </div>
          </el-scrollbar>
        </div>

        <!-- 右侧：已选择 -->
        <div class="dialog-right">
          <div class="selected-header">
            <span>已选择 {{ selectedHandlers.length }} 人</span>
          </div>
          <el-scrollbar height="440px" style="border: 1px solid #dcdfe6; border-radius: 4px; margin-top: 12px">
            <div class="selected-list">
              <el-tag v-for="handler in selectedHandlers" :key="handler.value" type="success" closable
                @close="removeHandlerSelection(handler.value)" style="margin: 4px">
                {{ handler.label }}
              </el-tag>
              <el-empty v-if="selectedHandlers.length === 0" description="未选择" :image-size="80" />
            </div>
          </el-scrollbar>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 货品选择对话框 -->
    <el-dialog v-model="productDialogVisible" title="添加货品" width="900px" :close-on-click-modal="false"
      class="product-dialog" @close="handleProductDialogClose">
      <!-- 搜索栏 -->
      <div class="product-search-container">
        <div class="search-title">
          <el-icon style="margin-right: 8px">
            <Search />
          </el-icon>
          <span>货品查询</span>
        </div>
        <div class="product-search-bar">
          <el-form :inline="true" class="search-form">
            <el-form-item label="产品名称">
              <el-input v-model="productSearchForm.ProductName" placeholder="请输入产品名称" clearable style="width: 200px"
                @clear="handleProductSearch" @keyup.enter="handleProductSearch">
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="单位">
              <el-select v-model="productSearchForm.Unit" placeholder="请选择单位" clearable style="width: 140px"
                @clear="handleProductSearch">
                <el-option v-for="unit in productUnitList" :key="unit.value" :label="unit.label" :value="unit.label" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleProductSearch" :icon="Search">查询</el-button>
              <el-button @click="handleProductReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 已选择提示 -->
      <div v-if="selectedProducts.length > 0" class="selected-tip">
        <el-alert :title="`已选择 ${selectedProducts.length} 个货品`" type="success" :closable="false" show-icon />
      </div>

      <!-- 货品列表 -->
      <div class="product-table-container">
        <el-table :data="productList" border stripe style="width: 100%" @selection-change="handleProductSelectionChange"
          height="320" :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }">
          <el-table-column type="selection" width="50" fixed="left" />
          <el-table-column type="index" label="序号" width="60" fixed="left" align="center" />
          <el-table-column prop="productCode" label="货品编号" width="110" show-overflow-tooltip />
          <el-table-column prop="productName" label="货品名称" min-width="140" show-overflow-tooltip>
            <template #default="{ row }">
              <div style="font-weight: 500; color: #303133">{{ row.productName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="specificationModel" label="规格型号" width="110" show-overflow-tooltip />
          <el-table-column prop="unit" label="单位" width="80" align="center">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.unit }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inboundUnitPrice" label="入库单价" width="100" align="right">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: 500">¥{{ row.inboundUnitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="currentInventory" label="当前库存" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.currentInventory > 0 ? 'success' : 'danger'" size="small">
                {{ row.currentInventory }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="product-pagination">
        <div class="pagination-info">
          <el-icon style="margin-right: 6px">
            <InfoFilled />
          </el-icon>
          <span>总共 <strong style="color: #409eff">{{ productTotal }}</strong> 条记录</span>
        </div>
        <el-pagination v-model:current-page="productCurrentPage" v-model:page-size="productPageSize"
          :page-sizes="[10, 20, 50, 100]" layout="sizes, prev, pager, next, jumper" :total="productTotal"
          @size-change="handleProductPageSizeChange" @current-change="handleProductPageChange" background />
      </div>

      <template #footer>
        <div class="product-dialog-footer">
          <div class="footer-info">
            <el-icon style="margin-right: 6px; color: #909399">
              <Warning />
            </el-icon>
            <span style="color: #909399; font-size: 13px">提示：可以多选货品后批量添加</span>
          </div>
          <div class="footer-actions">
            <el-button @click="handleProductDialogClose">取消</el-button>
            <el-button type="primary" @click="handleConfirmProducts" :disabled="selectedProducts.length === 0">
              确定添加 ({{ selectedProducts.length }})
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 盘点明细 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">盘点明细</span>
        </div>
      </template>

      <div class="toolbar">
        <el-button type="success" @click="handleAddItem">添加</el-button>
        <el-button type="danger" @click="handleRemoveItems">移除</el-button>
        <el-button @click="handleImport">导入</el-button>
      </div>

      <el-alert title="请选择仓库!" type="warning" :closable="false" v-if="!formData.warehouse"
        style="margin-bottom: 12px" />
      <el-alert title="请选择货品!" type="warning" :closable="false" v-if="formData.warehouse && items.length === 0"
        style="margin-bottom: 12px" />

      <div class="table-container">
        <el-table :data="items" style="width: 100%" border stripe @selection-change="handleItemSelectionChange"
          max-height="500">
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column type="index" label="序号" width="60" fixed="left" />
          <el-table-column prop="name" label="货品名称" width="140" show-overflow-tooltip />
          <el-table-column prop="code" label="货品编号" width="140" show-overflow-tooltip />
          <el-table-column prop="spec" label="规格型号" width="120" show-overflow-tooltip />
          <el-table-column prop="unit" label="单位" width="90" align="center" />
          <el-table-column prop="bookStock" label="账面库存" width="110" align="center">
            <template #default="{ row }">
              {{ isCompositeUnit(row.unit) ? parseBookStock(row.bookStock, row.unit) : (row.bookStock || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="bookAmount" label="账面金额" width="120" align="right">
            <template #default="{ row }">
              <span style="color: #409eff; font-weight: 500">¥{{ row.bookAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryLocation" label="盘点库位" width="150">
            <template #default="{ row, $index }">
              <el-select v-model="row.inventoryLocation" placeholder="请选择库位" size="small" filterable clearable
                @change="handleInventoryLocationChange($index)">
                <el-option v-for="location in storagelocationList" :key="location.value" :label="location.label"
                  :value="location.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryQuantity" label="盘点数量" width="120" align="center">
            <template #default="{ row, $index }">
              <el-input
                :model-value="isCompositeUnit(row.unit) ? formatInventoryQuantity(Number(row.inventoryQuantity) || 0, row.unit) : (row.inventoryQuantity || 0)"
                @input="(val: any) => handleInventoryQuantityInput(val, $index, row)"
                @blur="(e: any) => handleInventoryQuantityBlur(e, $index, row)" placeholder="请先选择库位" size="small"
                :disabled="!row.inventoryLocation">
                <template #suffix v-if="isCompositeUnit(row.unit)">
                  <el-button text @click="openCompositeUnitDialog(row, $index)" :disabled="!row.inventoryLocation"
                    style="padding: 0; min-width: auto; height: auto; font-size: 16px; color: #909399;">
                    ...
                  </el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="difference" label="盈亏数量" width="110" align="center">
            <template #default="{ row }">
              <span
                :style="{ color: row.difference > 0 ? '#67c23a' : row.difference < 0 ? '#f56c6c' : '#909399', fontWeight: '500' }">
                {{ row.difference || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="盘点状态" width="110" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.status"
                :type="row.status === '盘盈' ? 'success' : row.status === '盘亏' ? 'danger' : 'primary'" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="referencePrice" label="参考单价" width="120" align="center">
            <template #default="{ row, $index }">
              <el-input v-model.number="row.referencePrice" placeholder="请输入" size="small"
                @input="handleReferencePriceChange($index)" />
            </template>
          </el-table-column>
          <el-table-column prop="profitLossAmount" label="盈亏金额" width="120" align="right">
            <template #default="{ row }">
              <span
                :style="{ color: row.profitLossAmount > 0 ? '#67c23a' : row.profitLossAmount < 0 ? '#f56c6c' : '#909399', fontWeight: '500' }">
                ¥{{ row.profitLossAmount || '0.00' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="180">
            <template #default="{ row }">
              <el-input v-model="row.remark" placeholder="请输入备注" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button link type="danger" size="small" @click="handleRemoveItem(row)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 自定义合计行 -->
        <div class="custom-summary-row" v-if="items.length > 0">
          <span class="summary-label">合计</span>
          <span class="summary-item">账面库存: <strong>{{ summaryData.bookStockTotal }}</strong></span>
          <span class="summary-item">账面金额: <strong>{{ summaryData.bookAmountTotal }}</strong></span>
          <span class="summary-item">盘点数量: <strong>{{ summaryData.inventoryQtyTotal }}</strong></span>
          <span class="summary-item">盘盈数量: <strong>{{ summaryData.profitCount }}</strong></span>
          <span class="summary-item">盘亏数量: <strong>{{ summaryData.lossCount }}</strong></span>
          <span class="summary-item">无盈亏数量: <strong>{{ summaryData.noChangeCount }}</strong></span>
          <span class="summary-item">盘盈金额: <strong>{{ summaryData.profitAmount }}</strong></span>
          <span class="summary-item">盘亏金额: <strong>{{ summaryData.lossAmount }}</strong></span>
        </div>
      </div>
    </el-card>

    <!-- 复合单位编辑对话框 -->
    <el-dialog v-model="compositeUnitDialogVisible" title="编辑" width="500px" :close-on-click-modal="false"
      class="composite-unit-dialog">
      <el-table :data="compositeUnitData" border style="width: 100%">
        <el-table-column prop="序号" label="序号" width="80" align="center">
          <template #default="{ $index }">{{ $index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="100" align="center" />
        <el-table-column prop="unit" label="单位" width="100" align="center" />
        <el-table-column prop="inventoryQty" label="盘点数量" align="center">
          <template #default="{ row }">
            <el-input v-model.number="row.inventoryQty" size="small" @input="handleCompositeUnitChange" />
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
        <div style="display: flex; gap: 30px;">
          <span style="font-size: 14px; color: #606266;">
            盈亏数量: <strong style="font-weight: 700; color: #333;">{{ compositeUnitDifference }}</strong>
          </span>
          <span style="font-size: 14px; color: #606266;">
            盈亏状态:
            <el-tag v-if="compositeUnitStatus"
              :type="compositeUnitStatus === '盘盈' ? 'success' : compositeUnitStatus === '盘亏' ? 'danger' : 'info'"
              size="small">
              {{ compositeUnitStatus }}
            </el-tag>
          </span>
        </div>
      </div>

      <template #footer>
        <el-button @click="compositeUnitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCompositeUnit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 上传附件 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">上传附件</span>
        </div>
      </template>

      <el-upload ref="uploadRef" v-model:file-list="fileList" :auto-upload="false" :on-change="handleFileChange"
        :on-remove="handleFileRemove" accept=".doc,.docx,.pdf,.rar,.zip,.txt,.xls,.xlsx" :limit="10"
        class="upload-container" drag>
        <div class="upload-dragger">
          <el-icon class="upload-icon">
            <Upload />
          </el-icon>
          <div class="upload-text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="upload-tip">支持上传 doc、pdf、rar、zip 等格式文档,单个文件上传最大200MB,最多10个文件</div>
        </div>
      </el-upload>
    </el-card>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <el-button @click="handleClose">关闭</el-button>
      <el-button @click="handleSaveDraft">保存为草稿</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import { MoreFilled, Search, Check, InfoFilled, Warning, Upload } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
// 导入API接口
import {
  getInventoryCode,
  saveInventoryDraft,
  saveInventory,
  SaveInventory,
  getProductList,
  queryProduct,
  getProductUnitList,
  getDeptCascader,
  getHandlerInfoList,
  queryWarehouse,
  queryStoragelocation,
  getInventoryTypeList,
  getInventoryDetail
} from '@/api/inventory'
import useRender from 'element-plus/es/components/table/src/table-body/render-helper.mjs'

const router = useRouter()
const route = useRoute()

// 是否为编辑模式
const isEditMode = ref(false)
const currentInventoryId = ref(0)

// 表单数据
const formData = reactive({
  code: '', // 盘点单号,从后端获取
  type: '',
  startTime: '',
  endTime: '',
  warehouse: '',
  operator: 1,
  remark: '',
  inventoryTypeId: ''
})

// 仓库列表
const warehouseList = ref<any[]>([]) // 仓库列表数据

// 库位列表
const storagelocationList = ref<any[]>([]) // 库位列表数据
const inventoryTypeList = ref<any[]>([]) // 盘点类型列表数据

// 货品选择对话框相关
const productDialogVisible = ref(false) // 货品对话框显示状态
const productSearchForm = reactive({
  ProductName: '', // 产品名称
  Unit: '' // 单位
})

const productList = ref<any[]>([]) // 货品列表
const productUnitList = ref<any[]>([{
  value: 1,
  label: "台"
},
{
  value: 2,
  label: "部"
},
{
  value: 3,
  label: "副"
},
{
  value: 4,
  label: "个"
},
{
  value: 5,
  label: "条"
},
{
  value: 6,
  label: "包"
},]) // 单位列表
const selectedProducts = ref<any[]>([]) // 已选择的货品
const productCurrentPage = ref(1) // 当前页
const productPageSize = ref(10) // 每页条数
const productTotal = ref(0) // 总条数

// 经办人选择对话框相关
const handlerDialogVisible = ref(false) // 对话框显示状态
const deptTreeRef = ref() // 部门树组件引用

// 部门相关
const deptTreeData = ref<any[]>([]) // 部门树形数据
const deptTreeProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}
const deptSearchKeyword = ref('') // 部门搜索关键词
const currentSelectedDept = ref<any>(null) // 当前选中的部门

// 经办人相关
const handlerList = ref<any[]>([]) // 当前部门的经办人列表
const handlerSearchKeyword = ref('') // 经办人搜索关键词
const selectedHandlers = ref<any[]>([]) // 已选择的经办人
const selectedHandlerName = ref('') // 显示在输入框中的经办人名称

// LocalStorage 键名
const STORAGE_KEY = 'inventory_add_items'

// 从 LocalStorage 加载数据
const loadItemsFromStorage = () => {
  try {
    const savedData = localStorage.getItem(STORAGE_KEY)
    if (savedData) {
      return JSON.parse(savedData)
    }
  } catch (error) {
    console.error('加载本地数据失败:', error)
  }
  return []
}

// 保存数据到 LocalStorage
const saveItemsToStorage = (data: any[]) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch (error) {
    console.error('保存本地数据失败:', error)
  }
}

// 清空 LocalStorage
const clearItemsFromStorage = () => {
  try {
    localStorage.removeItem(STORAGE_KEY)
  } catch (error) {
    console.error('清空本地数据失败:', error)
  }
}

// 清空表单数据
const resetFormData = () => {
  // 清空表单字段
  formData.type = ''
  formData.startTime = ''
  formData.endTime = ''
  formData.warehouse = ''
  formData.operator = 1
  formData.remark = ''
  formData.inventoryTypeId = ''

  // 清空盘点明细
  items.value = []
  selectedItems.value = []

  // 清空附件
  fileList.value = []

  // 清空经办人选择
  selectedHandlers.value = []
  selectedHandlerName.value = ''

  // 清空本地存储
  clearItemsFromStorage()

  // 重新获取盘点单号
  fetchInventoryCode()
}

// 盘点明细数据 - 从 LocalStorage 初始化
const items = ref<any[]>(loadItemsFromStorage())

const selectedItems = ref<any[]>([])

// 文件列表
const fileList = ref<UploadFile[]>([])

// 复合单位编辑对话框
const compositeUnitDialogVisible = ref(false)
const compositeUnitData = ref<any[]>([])
const currentEditingRow = ref<any>(null)
const currentEditingIndex = ref<number>(-1)

// ==================== API接口预留区域 ====================

/**
 * 获取系统自动编号
 * API: GET /api/inventory/getCode
 */
const fetchInventoryCode = async () => {
  try {
    const response: any = await getInventoryCode()
    formData.code = response.data?.code || '自动获取系统编号'
  } catch (error) {
    // 开发阶段：后端接口未实现时使用模拟数据
    console.warn('API未实现,使用模拟数据')
    formData.code = '自动获取系统编号'
    // ElMessage.error('获取盘点单号失败')
  }
}

/**
 * 获取仓库列表
 * API: GET http://localhost:5110/api/Warehouse/QueryWarehouse
 */
const fetchWarehouseList = async () => {
  try {
    const response: any = await queryWarehouse()
    console.log('仓库API返回数据:', response)

    if (response.code === 200 && response.data) {
      // 将返回的数据转换为 select 需要的格式
      warehouseList.value = response.data.data.map((item: any) => ({
        value: item.warehouseID || item.id || item.warehouseID,
        label: item.warehouseName || item.name || item.warehouseName,
        raw: item
      }))
      console.log('仓库列表加载成功,共', warehouseList.value.length, '个仓库:', warehouseList.value)
    } else {
      warehouseList.value = []
      ElMessage.warning(response.message || '获取仓库列表失败')
    }
  } catch (error: any) {
    console.error('获取仓库列表失败:', error)
    warehouseList.value = []
    ElMessage.error('获取仓库列表失败,请检查网络连接')
  }
}

/**
 * 获取库位列表
 * API: GET http://localhost:5110/api/Storagelocation/QueryStoragelocation
 */
const fetchStoragelocationList = async () => {
  try {
    const response: any = await queryStoragelocation()


    if (response.code === 200 && response.data.data) {
      console.log(response.data.data)
      // 将返回的数据转换为 select 需要的格式
      storagelocationList.value = response.data.data.map((item: any) => ({
        value: item.storagelocationId,
        label: item.storagelocationName,
        raw: item
      }))
      console.log('库位列表加载成功,共', storagelocationList.value.length, '个库位:', storagelocationList.value)
    } else {
      storagelocationList.value = []
      ElMessage.warning(response.message || '获取库位列表失败')
    }
  } catch (error: any) {
    console.error('获取库位列表失败:', error)
    storagelocationList.value = []
    ElMessage.error('获取库位列表失败,请检查网络连接')
  }
}

/**
 * 获取盘点类型列表
 * API: GET http://localhost:5110/api/InventoryType/GetInventoryTypeList
 */
const fetchInventoryTypeList = async () => {
  try {
    const response: any = await getInventoryTypeList()

    if (response.code === 200 && response.data) {
      console.log('盘点类型数据:', response.data)
      // 将返回的数据转换为 select 需要的格式
      inventoryTypeList.value = response.data.map((item: any) => ({
        value: item.inventoryTypeId || item.id || item.value,
        label: item.inventoryTypeName || item.name || item.label,
        raw: item
      }))
      console.log('盘点类型列表加载成功,共', inventoryTypeList.value.length, '个类型:', inventoryTypeList.value)
    } else {
      inventoryTypeList.value = []
      ElMessage.warning(response.message || '获取盘点类型列表失败')
    }
  } catch (error: any) {
    console.error('获取盘点类型列表失败:', error)
    inventoryTypeList.value = []
    ElMessage.error('获取盘点类型列表失败,请检查网络连接')
  }
}

/**
 * 加载盘点详情数据（编辑模式）
 * API: GET http://localhost:5110/api/Inventory/GetInventoryDetail?InventoryCode=?
 */
const loadInventoryDetail = async (inventoryCode: string) => {
  try {
    // 确保库位列表已加载（编辑时需要根据ID显示名称）
    if (storagelocationList.value.length === 0) {
      await fetchStoragelocationList()
    }
    
    const response: any = await getInventoryDetail(inventoryCode)
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 保存 inventoryId
      currentInventoryId.value = data.inventoryId || 0
      
      // 填充表单数据
      formData.code = data.inventoryCode || ''
      formData.inventoryTypeId = data.inventoryTypeId || ''
      formData.startTime = data.inventoryDateTime || ''
      formData.endTime = data.inventoryEndTime || ''
      formData.warehouse = data.warehouseId || ''
      formData.remark = data.inventoryContent || ''
      
      // 根据仓库ID加载库位列表（如果还没有加载）
      if (data.warehouseId && storagelocationList.value.length === 0) {
        await fetchStoragelocationList()
      }
      
      // 设置经办人
      if (data.handlerrId) {
        formData.operator = data.handlerrId
        selectedHandlerName.value = data.handlerName || ''
        
        // 如果有部门ID，先加载部门数据，然后设置经办人
        if (data.warehouseDeptId) {
          await fetchDeptTreeData()
          await fetchHandlerList(data.warehouseDeptId)
          
          // 设置选中的经办人
          selectedHandlers.value = [{
            value: data.handlerrId,
            label: data.handlerName,
            raw: { handlerrId: data.handlerrId, handlerName: data.handlerName }
          }]
        }
      }
      
      // 填充盘点明细
      if (data.detailsList && data.detailsList.length > 0) {
        items.value = data.detailsList.map((detail: any) => {
          const unit = detail.detailsUnit || ''
          
          // 解析账面库存（使用 parseBookStock 函数正确处理复合单位）
          const bookStock = parseBookStock(detail.bookStock, unit)
          
          // 解析盘点数量
          let inventoryQuantity = 0
          if (isCompositeUnit(unit)) {
            // 对于复合单位，优先使用 countedStockRaw，然后是 countedStockNumeric，最后是 countedStock
            if (detail.countedStockRaw) {
              inventoryQuantity = parseInventoryQuantity(detail.countedStockRaw, unit)
            } else if (detail.countedStockNumeric) {
              inventoryQuantity = Number(detail.countedStockNumeric) || 0
            } else {
              inventoryQuantity = Number(detail.countedStock) || 0
            }
          } else {
            inventoryQuantity = Number(detail.countedStock || detail.countedStockNumeric) || 0
          }
          
          return {
            // items 数组的字段名
            name: detail.detailsProductName || '',
            code: detail.detailsProductCode || '',
            spec: detail.specificationModel || '',
            unit: detail.detailsUnit || '',
            bookStock: bookStock, // 已正确解析的账面库存（瓶数）
            bookAmount: detail.bookAmount || '0.00',
            inventoryQuantity: inventoryQuantity, // 已正确解析的盘点数量（瓶数）
            inventoryLocation: detail.countedStockLocation ? Number(detail.countedStockLocation) : '',
            referencePrice: Number(detail.referencePrice) || 0,
            profitLossAmount: String(detail.profitLossAmount || '0.00'),
            difference: Number(detail.profitLossQty) || 0,
            status: detail.status === 1 ? '盘盈' : detail.status === 2 ? '盘亏' : '无盈亏',
            remark: detail.remark || '',
            // 保存原始详情ID用于更新
            inventoryCheckDetailsId: detail.inventory_check_detailsId
          }
        })
        
        // 重新计算每个明细项的盈亏（因为账面库存和盘点数量可能已更新）
        items.value.forEach((item: any, index: number) => {
          calculateItemDifference(index)
        })
        
        // 保存到本地存储
        saveItemsToStorage(items.value)
      }
      
      // 填充附件列表
      if (data.attachmentList && data.attachmentList.length > 0) {
        fileList.value = data.attachmentList.map((attachment: any) => ({
          name: attachment.uploadUrl || '',
          url: attachment.uploadUrl || '',
          uid: attachment.uploadId || Date.now(),
          status: 'success' as const,
          raw: attachment
        }))
      }
      
      ElMessage.success('加载盘点详情成功')
    } else {
      ElMessage.error(response.message || '加载盘点详情失败')
    }
  } catch (error: any) {
    console.error('加载盘点详情失败:', error)
    ElMessage.error(error.message || '加载盘点详情失败,请稍后重试')
  }
}

/**
 * 获取部门树形数据
 * API: GET http://localhost:5110/api/WarehouseDept/GetDeptCascader?parentId=0
 */
const fetchDeptTreeData = async () => {
  try {
    const response: any = await getDeptCascader(0)
    if (response.code === 200 && response.data) {
      deptTreeData.value = response.data
      console.log('部门树形数据加载成功:', deptTreeData.value)
    } else {
      ElMessage.error(response.message || '获取部门数据失败')
    }
  } catch (error: any) {
    console.error('获取部门数据失败:', error)
    ElMessage.error('获取部门数据失败,请检查网络连接')
  }
}

/**
 * 根据部门ID获取经办人列表
 * API: GET http://localhost:5110/api/HandlerInfo/GetHandlerInfoList?warehouseDeptId=?
 */
const fetchHandlerList = async (warehouseDeptId: number) => {
  try {
    const response: any = await getHandlerInfoList(warehouseDeptId)
    console.log('经办人API返回数据:', response)

    if (response.code === 200 && response.data) {
      // 将返回的数据转换为 select 需要的格式
      const tempList = response.data.map((item: any, index: number) => {
        // 尝试多种可能的ID字段名（注意：后端字段是handlerrId,两个r）
        let handlerId = item.handlerrId || item.handlerId || item.id || item.userId || item.handlerid
        const handlerName = item.handlerName || item.name || item.userName || item.handlename || `经办人${index + 1}`

        // 如果ID为undefined、null、0或空字符串,使用时间戳+索引生成唯一ID
        if (!handlerId || handlerId === 0) {
          handlerId = `temp_${Date.now()}_${index}`
          console.warn(`经办人"${handlerName}"缺少有效ID,已自动生成临时ID:`, handlerId)
        }

        console.log(`经办人${index + 1}:`, { 原始数据: item, ID: handlerId, 名称: handlerName })

        return {
          value: handlerId,
          label: handlerName,
          raw: item // 保存原始数据,方便调试
        }
      })

      // 检查是否有重复的ID
      const ids = tempList.map((h: any) => h.value)
      const uniqueIds = new Set(ids)
      if (ids.length !== uniqueIds.size) {
        console.error('错误：检测到重复的经办人ID！', ids)
        console.error('重复的ID:', ids.filter((id: any, index: any) => ids.indexOf(id) !== index))
        ElMessage.error('数据异常：检测到重复的经办人ID,请联系后端开发人员检查数据')

        // 强制使每个ID唯一
        handlerList.value = tempList.map((handler: any, index: number) => ({
          ...handler,
          value: `${handler.value}_${index}` // 添加索引确保唯一
        }))
      } else {
        handlerList.value = tempList
      }

      console.log('经办人列表加载成功,共', handlerList.value.length, '人:', handlerList.value)
    } else {
      handlerList.value = []
      ElMessage.warning(response.message || '该部门暂无经办人')
    }
  } catch (error: any) {
    console.error('获取经办人列表失败:', error)
    handlerList.value = []
    ElMessage.error('获取经办人列表失败,请检查网络连接')
  }
}

/**
 * 保存盘点单（草稿）
 * API: POST /api/inventory/saveDraft
 */
const saveDraft = async () => {
  try {
    const params = {
      ...formData,
      items: items.value,
      files: fileList.value.map(f => f.name)
    }

    console.log('保存草稿参数:', params)

    const response: any = await saveInventoryDraft(params)
    return response.data || { success: true, message: '保存草稿成功' }
  } catch (error) {
    // 开发阶段：后端接口未实现时使用模拟返回
    console.warn('API未实现,使用模拟数据')
    return { success: true, message: '保存草稿成功' }
    // throw new Error('保存草稿失败')
  }
}

/**
 * 保存盘点单（正式）
 * API: POST /api/inventory/save
 */
const saveInventoryData = async () => {
  try {
    const params = {
      ...formData,
      items: items.value,
      files: fileList.value.map(f => f.name)
    }

    console.log('保存参数:', params)

    const response: any = await saveInventory(params)
    return response.data || { success: true, message: '保存成功' }
  } catch (error) {
    // 开发阶段：后端接口未实现时使用模拟返回
    console.warn('API未实现,使用模拟数据')
    return { success: true, message: '保存成功' }
    // throw new Error('保存失败')
  }
}

/**
 * 获取货品列表
 * API: GET /api/products/list
 */
const fetchProducts = async (warehouseId: string) => {
  try {
    const response: any = await getProductList({ warehouseId })
    return response.data || []
  } catch (error) {
    // 开发阶段：后端接口未实现时使用空数组
    console.warn('API未实现,使用模拟数据')
    return []
    // throw new Error('获取货品列表失败')
  }
}

/**
 * 查询货品列表（新接口）
 * API: GET http://localhost:5110/api/Product/QueryProduct
 */
const fetchProductList = async () => {
  try {
    const params = {
      PageIndex: productCurrentPage.value,
      PageSize: productPageSize.value,
      ProductName: productSearchForm.ProductName || undefined,
      Unit: productSearchForm.Unit || undefined,
      WarehouseId: formData.warehouse ? Number(formData.warehouse) : undefined
    }

    console.log('查询货品参数:', params)

    const response: any = await queryProduct(params)
    console.log('货品API返回数据:', response)

    if (response.code === 200 && response.data) {
      // 转换数据格式
      productList.value = response.data.data.map((item: any) => ({
        productId: item.productId || item.productId,
        productCode: item.productCode || '',
        productName: item.productName || '',
        specificationModel: item.specificationModel || '',
        unit: item.unit || '',
        inboundUnitPrice: item.inboundUnitPrice || 0,
        currentInventory: item.currentInventory || item.currentInventory || 0,
        raw: item
      }))

      productTotal.value = response.data.totalCount || 0
      console.log('货品列表加载成功,共', productTotal.value, '条')
    } else {
      productList.value = []
      productTotal.value = 0
      ElMessage.warning(response.message || '获取货品列表失败')
    }
  } catch (error: any) {
    console.error('获取货品列表失败:', error)
    productList.value = []
    productTotal.value = 0
    ElMessage.error('获取货品列表失败,请检查网络连接')
  }
}

/**
 * 获取货品单位列表
 * API: GET http://localhost:5110/api/Product/GetProductUnitList
 */
const fetchProductUnitList = async () => {

}

// ==================== 页面逻辑 ====================

// 验证时间范围
const validateTimeRange = (): boolean => {
  if (!formData.startTime || !formData.endTime) {
    return true // 如果有一个为空,暂不验证,等保存时再验证
  }

  const startTime = new Date(formData.startTime).getTime()
  const endTime = new Date(formData.endTime).getTime()

  if (startTime > endTime) {
    ElMessageBox.alert(
      '盘点开始时间不能大于盘点结束时间,请重新选择！',
      '时间验证失败',
      {
        confirmButtonText: '确定',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    return false
  }

  return true
}

// 开始时间变化事件
const handleStartTimeChange = () => {
  if (formData.startTime && formData.endTime) {
    validateTimeRange()
  }
}

// 结束时间变化事件
const handleEndTimeChange = () => {
  if (formData.startTime && formData.endTime) {
    validateTimeRange()
  }
}

// 初始化
// 初始化数据
fetchWarehouseList() // 加载仓库列表
fetchStoragelocationList() // 加载库位列表
fetchInventoryTypeList() // 加载盘点类型列表
fetchDeptTreeData() // 加载部门树形数据

// 监听路由变化，判断是否为编辑模式
onMounted(async () => {
  const code = route.query.code as string
  const mode = route.query.mode as string
  
  if (code && mode === 'edit') {
    // 编辑模式：加载详情数据
    isEditMode.value = true
    await loadInventoryDetail(code)
  } else {
    // 新增模式：获取新的盘点单号
    fetchInventoryCode()
  }
})

// 监听盘点明细数据变化,自动保存到 LocalStorage
watch(items, (newItems) => {
  saveItemsToStorage(newItems)
}, { deep: true })

// 监听部门搜索关键词变化
watch(deptSearchKeyword, (val) => {
  deptTreeRef.value?.filter(val)
})

// 部门树过滤方法
const filterDeptNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

// 计算过滤后的经办人列表
const filteredHandlerList = computed(() => {
  if (!handlerSearchKeyword.value) {
    return handlerList.value
  }
  return handlerList.value.filter((handler: any) =>
    handler.label.includes(handlerSearchKeyword.value)
  )
})

// 打开经办人选择对话框
const handleOpenHandlerDialog = () => {
  handlerDialogVisible.value = true
}

// 关闭对话框
const handleDialogClose = () => {
  handlerDialogVisible.value = false
  // 清空搜索关键词
  deptSearchKeyword.value = ''
  handlerSearchKeyword.value = ''
}

// 部门节点点击事件
const handleDeptNodeClick = (data: any) => {
  console.log('选中的部门:', data)
  currentSelectedDept.value = data

  // 加载该部门的经办人列表
  fetchHandlerList(data.value)
}

// 判断经办人是否已选中
const isHandlerSelected = (handlerId: any) => {
  return selectedHandlers.value.some((h: any) => h.value === handlerId)
}

// 切换经办人选择状态
const toggleHandlerSelection = (handler: any) => {
  console.log('点击经办人:', handler)
  console.log('当前已选择列表:', selectedHandlers.value)

  const index = selectedHandlers.value.findIndex((h: any) => h.value === handler.value)
  console.log('在已选择列表中的索引:', index)

  if (index > -1) {
    // 已选中,取消选择
    selectedHandlers.value.splice(index, 1)
    console.log('取消选择,剩余:', selectedHandlers.value)
  } else {
    // 未选中,添加选择
    selectedHandlers.value.push(handler)
    console.log('添加选择,当前:', selectedHandlers.value)
  }
}

// 移除已选择的经办人
const removeHandlerSelection = (handlerId: any) => {
  const index = selectedHandlers.value.findIndex((h: any) => h.value === handlerId)
  if (index > -1) {
    selectedHandlers.value.splice(index, 1)
  }
}

// 确认选择
const handleConfirmSelection = () => {
  if (selectedHandlers.value.length === 0) {
    ElMessage.warning('请至少选择一个经办人')
    return
  }

  // 将选中的经办人信息保存到表单
  // 这里可以根据需求决定保存单个还是多个
  // 如果只需要一个,取第一个
  const selectedValue = selectedHandlers.value[0].value

  // 确保ID是有效的数字
  const numericValue = Number(selectedValue)
  if (isNaN(numericValue) || numericValue === 0) {
    ElMessage.error('该经办人数据异常（ID无效）,请选择其他经办人或联系后端开发人员')
    console.error('经办人ID无效:', {
      原始值: selectedValue,
      转换后: numericValue,
      经办人数据: selectedHandlers.value[0]
    })
    return
  }

  formData.operator = numericValue

  // 显示所有选中的经办人名称
  selectedHandlerName.value = selectedHandlers.value.map((h: any) => h.label).join('、')

  console.log('✅ 经办人选择成功:', {
    ID: numericValue,
    名称: selectedHandlerName.value
  })

  ElMessage.success('选择成功')
  handleDialogClose()
}

// 打开货品选择对话框
const handleAddItem = () => {
  if (!formData.warehouse) {
    ElMessage.warning('请先选择仓库')
    return
  }

  productDialogVisible.value = true
  // 打开对话框时加载数据
  fetchProductUnitList()
  fetchProductList()
}

// 关闭货品选择对话框
const handleProductDialogClose = () => {
  productDialogVisible.value = false
  // 清空搜索条件
  productSearchForm.ProductName = ''
  productSearchForm.Unit = ''
  productCurrentPage.value = 1
  selectedProducts.value = []
}

// 货品查询
const handleProductSearch = () => {
  productCurrentPage.value = 1
  fetchProductList()
}

// 重置货品查询
const handleProductReset = () => {
  productSearchForm.ProductName = ''
  productSearchForm.Unit = ''
  productCurrentPage.value = 1
  fetchProductList()
}

// 货品选择变化
const handleProductSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection
  console.log('选中的货品:', selectedProducts.value)
}

// 货品分页大小变化
const handleProductPageSizeChange = (val: number) => {
  productPageSize.value = val
  fetchProductList()
}

// 货品页码变化
const handleProductPageChange = (val: number) => {
  productCurrentPage.value = val
  fetchProductList()
}

/**
 * 解析复合库存格式并计算账面金额
 * 例如："15瓶/8箱" + "瓶/箱(5瓶)" + 单价100 = 8箱*100 + 15瓶*20 = 1100
 */
const calculateBookAmount = (inventory: any, unit: string, unitPrice: number): string => {
  const price = Number(unitPrice) || 0

  // 如果库存是数字,直接计算
  if (typeof inventory === 'number') {
    return (inventory * price).toFixed(2)
  }

  const inventoryStr = String(inventory || '')

  // 解析单位中的换算关系,例如 "瓶/箱(5瓶)" -> 1箱=5瓶
  let conversionRate = 1
  const unitMatch = unit.match(/\((\d+).*?\)/)
  if (unitMatch) {
    conversionRate = parseInt(unitMatch[1])
  }

  // 解析库存格式,例如 "15瓶/8箱" 或 "8箱15瓶"
  let totalAmount = 0

  // 匹配 "数字+箱" 和 "数字+瓶" 格式
  const boxMatch = inventoryStr.match(/(\d+)\s*箱/)
  const bottleMatch = inventoryStr.match(/(\d+)\s*瓶/)

  if (boxMatch || bottleMatch) {
    const boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    const bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0

    // 单价是按箱计算的
    const pricePerBottle = conversionRate > 0 ? price / conversionRate : price

    // 总金额 = 箱数*箱单价 + 瓶数*瓶单价
    totalAmount = boxes * price + bottles * pricePerBottle
  } else {
    // 如果无法解析,尝试直接转数字
    const qty = parseFloat(inventoryStr) || 0
    totalAmount = qty * price
  }

  return totalAmount.toFixed(2)
}

// 确认选择货品
const handleConfirmProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一个货品')
    return
  }

  console.log('=== 开始添加货品 ===')
  console.log('当前盘点明细中的货品:', items.value.map(item => ({ code: item.code, name: item.name, unit: item.unit })))
  console.log('准备添加的货品:', selectedProducts.value.map(p => ({ code: p.productCode, name: p.productName, unit: p.unit })))

  // 检查重复的货品
  const duplicateProducts: string[] = []
  const newProducts: any[] = []

  selectedProducts.value.forEach((product: any) => {
    // 检查是否已存在（根据货品编号判断）
    const exists = items.value.some((item: any) => item.code === product.productCode)

    console.log(`检查货品 [${product.productName}] (编号: ${product.productCode}, 单位: ${product.unit}):`, exists ? '已存在' : '可添加')

    if (exists) {
      // 记录重复的货品名称
      duplicateProducts.push(product.productName)
    } else {
      // 记录需要添加的新货品
      newProducts.push(product)
    }
  })

  // 如果有重复的货品,给出提示
  if (duplicateProducts.length > 0) {
    const duplicateNames = duplicateProducts.join('、')
    console.log('发现重复货品:', duplicateNames)

    if (newProducts.length === 0) {
      // 全部都是重复的
      ElMessage.warning(`所选货品已在盘点明细中：${duplicateNames}`)
      return
    } else {
      // 部分重复
      ElMessage.warning(`以下货品已在盘点明细中,已自动跳过：${duplicateNames}`)
    }
  }

  // 添加新货品到盘点明细
  newProducts.forEach((product: any) => {
    const unitPrice = product.inboundUnitPrice || product.price || 0
    const inventory = product.currentInventory || product.stock || 0

    console.log(`添加货品: ${product.productName}, 编号: ${product.productCode}, 单位: ${product.unit}`)

    items.value.push({
      name: product.productName,
      code: product.productCode,
      spec: product.specificationModel || product.spec || '',
      unit: product.unit,
      bookStock: inventory,
      bookAmount: calculateBookAmount(inventory, product.unit, unitPrice),
      inventoryLocation: '',
      inventoryQuantity: 0,
      difference: 0,
      status: '无盈亏',
      referencePrice: unitPrice,
      profitLossAmount: '0.00',
      remark: ''
    })
  })

  if (newProducts.length > 0) {
    ElMessage.success(`成功添加 ${newProducts.length} 个货品`)
    console.log(`✓ 成功添加 ${newProducts.length} 个货品`)
  }

  console.log('添加后的盘点明细:', items.value.map(item => ({ code: item.code, name: item.name, unit: item.unit })))
  console.log('=== 添加货品完成 ===')

  handleProductDialogClose()
}

// 移除选中项
const handleRemoveItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要移除的项')
    return
  }

  selectedItems.value.forEach(item => {
    const index = items.value.findIndex(i => i.code === item.code)
    if (index > -1) {
      items.value.splice(index, 1)
    }
  })

  ElMessage.success('移除成功')
}

// 移除单个项
const handleRemoveItem = (row: any) => {
  const index = items.value.findIndex(i => i.code === row.code)
  if (index > -1) {
    items.value.splice(index, 1)
    ElMessage.success('移除成功')
  }
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 选择项变化
const handleItemSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

// 盘点库位变化
const handleInventoryLocationChange = (index: number) => {
  const item = items.value[index]
  console.log('盘点库位变化:', item.inventoryLocation)

  // 如果盘点库位为空（未选择或清空）,重置盘点数量为0
  if (!item.inventoryLocation || item.inventoryLocation === '') {
    console.log('盘点库位为空,重置盘点数量为0,所有字段恢复初始状态')
    item.inventoryQuantity = 0
  }

  // 重新计算盈亏数量、盘点状态、盈亏金额
  calculateItemDifference(index)
}

// 盘点数量输入事件（实时处理）
const handleInventoryQuantityInput = (value: any, index: number, row: any) => {
  // 解析输入值（支持"xx瓶/xx箱"格式或纯数字）
  const parsedValue = parseInventoryQuantity(value, row.unit)

  // 更新实际的盘点数量（保存为数字）
  row.inventoryQuantity = parsedValue

  // 重新计算盈亏
  calculateItemDifference(index)
}

// 盘点数量失焦事件（格式化显示）
const handleInventoryQuantityBlur = (event: FocusEvent, index: number, row: any) => {
  const item = items.value[index]

  // 确保有值
  if (item.inventoryQuantity === '' || item.inventoryQuantity === null || item.inventoryQuantity === undefined) {
    item.inventoryQuantity = 0
  }

  // 对于复合单位,确保值是数字格式（格式化显示在输入框的model-value中处理）
  if (isCompositeUnit(item.unit)) {
    item.inventoryQuantity = Number(item.inventoryQuantity) || 0
  }

  // 重新计算盈亏
  calculateItemDifference(index)
}

// 参考单价变化
const handleReferencePriceChange = (index: number) => {
  const item = items.value[index]
  // 确保输入的是数字
  if (item.referencePrice === '' || item.referencePrice === null) {
    item.referencePrice = 0
  }
  calculateItemDifference(index)
}

// 判断是否为复合单位（如：瓶/箱(6瓶)）
const isCompositeUnit = (unit: string) => {
  if (!unit) return false
  // 判断是否包含 "箱" 和括号
  return unit.includes('箱') && unit.includes('(') && unit.includes(')')
}

// 将数字转换为"xx瓶/xx箱"格式
const formatInventoryQuantity = (quantity: number, unit: string): string => {
  if (!isCompositeUnit(unit) || !quantity || quantity === 0) {
    return String(quantity || 0)
  }

  // 解析单位中的换算率,例如 "瓶/箱(5瓶)" -> 1箱=5瓶
  const unitMatch = unit.match(/\((\d+)/)
  const conversionRate = unitMatch ? parseInt(unitMatch[1]) : 1

  if (conversionRate <= 0) {
    return String(quantity)
  }

  // 计算箱数和剩余瓶数
  const boxes = Math.floor(quantity / conversionRate)
  const bottles = quantity % conversionRate

  // 格式化显示
  if (boxes > 0 && bottles > 0) {
    return `${bottles}瓶/${boxes}箱`
  } else if (boxes > 0) {
    return `${boxes}箱`
  } else if (bottles > 0) {
    return `${bottles}瓶`
  }

  return '0'
}

// 解析盘点数量（支持"xx瓶/xx箱"格式或纯数字）
const parseInventoryQuantity = (value: any, unit: string): number => {
  if (typeof value === 'number') {
    return value
  }

  const valueStr = String(value || '').trim()

  // 如果不是复合单位或为空,直接转换数字
  if (!isCompositeUnit(unit) || !valueStr) {
    const num = parseFloat(valueStr)
    return isNaN(num) ? 0 : num
  }

  // 解析"xx瓶/xx箱"格式
  const boxMatch = valueStr.match(/(\d+)\s*箱/)
  const bottleMatch = valueStr.match(/(\d+)\s*瓶/)

  // 如果匹配到格式,解析并计算
  if (boxMatch || bottleMatch) {
    const unitMatch = unit.match(/\((\d+)/)
    const conversionRate = unitMatch ? parseInt(unitMatch[1]) : 1

    const boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    const bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0

    return bottles + (boxes * conversionRate)
  }

  // 如果只是纯数字,直接转换
  const num = parseFloat(valueStr)
  return isNaN(num) ? 0 : num
}

// 解析账面库存数量（处理复合单位）
const parseBookStock = (bookStock: any, unit: string): number => {
  // 如果是数字,直接返回
  if (typeof bookStock === 'number') {
    return bookStock
  }

  const stockStr = String(bookStock || '')

  // 检查是否是复合单位
  if (isCompositeUnit(unit)) {
    // 解析单位中的换算率,例如 "瓶/箱(5瓶)" -> 1箱=5瓶
    let conversionRate = 1
    const unitMatch = unit.match(/\((\d+)/)
    if (unitMatch) {
      conversionRate = parseInt(unitMatch[1])
    }

    // 解析库存格式,例如 "5瓶16箱" 或 "16箱5瓶"
    const boxMatch = stockStr.match(/(\d+)\s*箱/)
    const bottleMatch = stockStr.match(/(\d+)\s*瓶/)

    const boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    const bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0

    // 转换成瓶数总计
    return bottles + (boxes * conversionRate)
  }

  // 非复合单位,尝试直接转换为数字
  const num = parseFloat(stockStr)
  return isNaN(num) ? 0 : num
}

// 计算盈亏（统一计算方法）
const calculateItemDifference = (index: number) => {
  const item = items.value[index]

  // 盈亏数量 = 盘点数量 - 账面库存
  const inventoryQty = Number(item.inventoryQuantity) || 0
  const bookStock = parseBookStock(item.bookStock, item.unit)
  item.difference = inventoryQty - bookStock

  // 盘点状态
  if (item.difference > 0) {
    item.status = '盘盈'
  } else if (item.difference < 0) {
    item.status = '盘亏'
  } else {
    item.status = '无盈亏'
  }

  // 盈亏金额 = 盈亏数量 * 参考单价
  const referencePrice = Number(item.referencePrice) || 0
  const profitLoss = item.difference * referencePrice
  item.profitLossAmount = profitLoss.toFixed(2)
}

// 打开复合单位编辑对话框
const openCompositeUnitDialog = (row: any, index: number) => {
  currentEditingRow.value = row
  currentEditingIndex.value = index

  // 解析单位,例如 "瓶/箱(6瓶)" -> 1箱=6瓶
  const unit = row.unit || ''
  const match = unit.match(/\((\d+)/)
  const conversionRate = match ? parseInt(match[1]) : 6 // 默认6瓶一箱

  // 解析账面库存,例如 "5瓶16箱" 或 "16箱5瓶"
  const bookStockStr = String(row.bookStock || '')
  const boxMatch = bookStockStr.match(/(\d+)\s*箱/)
  const bottleMatch = bookStockStr.match(/(\d+)\s*瓶/)

  const currentBoxes = boxMatch ? parseInt(boxMatch[1]) : 0
  const currentBottles = bottleMatch ? parseInt(bottleMatch[1]) : 0

  // 设置对话框数据
  compositeUnitData.value = [
    {
      currentStock: currentBottles,
      unit: '瓶',
      inventoryQty: 0,
      conversionRate: 1
    },
    {
      currentStock: currentBoxes,
      unit: `箱 (${conversionRate}瓶)`,
      inventoryQty: 0,
      conversionRate: conversionRate
    }
  ]

  compositeUnitDialogVisible.value = true
}

// 复合单位盈亏数量计算
const compositeUnitDifference = computed(() => {
  if (compositeUnitData.value.length === 0) return 0

  // 计算总盘点数量（瓶数 + 箱数*换算率）
  const totalInventory = compositeUnitData.value.reduce((sum, item) => {
    return sum + (Number(item.inventoryQty) || 0) * item.conversionRate
  }, 0)

  // 计算总账面库存
  const totalBook = compositeUnitData.value.reduce((sum, item) => {
    return sum + (Number(item.currentStock) || 0) * item.conversionRate
  }, 0)

  return totalInventory - totalBook
})

// 复合单位盈亏状态计算
const compositeUnitStatus = computed(() => {
  const diff = compositeUnitDifference.value
  if (diff > 0) return '盘盈'
  if (diff < 0) return '盘亏'
  return '无盈亏'
})

// 复合单位数量变化
const handleCompositeUnitChange = () => {
  // 触发重新计算
}

// 确认复合单位编辑
const confirmCompositeUnit = () => {
  if (currentEditingRow.value && currentEditingIndex.value !== -1) {
    // 计算总盘点数量
    const totalInventory = compositeUnitData.value.reduce((sum, item) => {
      return sum + (Number(item.inventoryQty) || 0) * item.conversionRate
    }, 0)

    // 更新盘点数量
    currentEditingRow.value.inventoryQuantity = totalInventory

    // 重新计算盈亏
    calculateItemDifference(currentEditingIndex.value)

    ElMessage.success('盘点数量已更新')
  }

  compositeUnitDialogVisible.value = false
}

// 计算合计数据
const summaryData = computed(() => {
  // 账面库存总数（正确解析复合单位）
  const bookStockTotal = items.value.reduce((sum: number, item: any) => {
    return sum + parseBookStock(item.bookStock, item.unit)
  }, 0)

  const bookAmountTotal = items.value.reduce((sum: number, item: any) => sum + (parseFloat(item.bookAmount) || 0), 0)
  const inventoryQtyTotal = items.value.reduce((sum: number, item: any) => sum + (Number(item.inventoryQuantity) || 0), 0)

  const profitItems = items.value.filter((item: any) => Number(item.difference) > 0)
  const lossItems = items.value.filter((item: any) => Number(item.difference) < 0)
  const noChangeItems = items.value.filter((item: any) => Number(item.difference) === 0)

  const profitAmount = items.value.reduce((sum: number, item: any) => {
    const amount = parseFloat(item.profitLossAmount) || 0
    return amount > 0 ? sum + amount : sum
  }, 0)
  const lossAmount = items.value.reduce((sum: number, item: any) => {
    const amount = parseFloat(item.profitLossAmount) || 0
    return amount < 0 ? sum + amount : sum
  }, 0)

  return {
    bookStockTotal,
    bookAmountTotal: bookAmountTotal.toFixed(2),
    inventoryQtyTotal,
    profitCount: profitItems.length,
    lossCount: lossItems.length,
    noChangeCount: noChangeItems.length,
    profitAmount: profitAmount.toFixed(2),
    lossAmount: Math.abs(lossAmount).toFixed(2)
  }
})

// 文件变化
const handleFileChange = (file: UploadFile) => {
  console.log('文件添加:', file.name)
}

// 删除文件
const handleFileRemove = (file: UploadFile) => {
  console.log('文件删除:', file.name)
}

// 仓库设置
const handleWarehouseSetting = () => {
  router.push('/warehouse/add')
}

// 关闭
const handleClose = () => {
  // 清空本地存储的盘点明细数据
  clearItemsFromStorage()
  router.back()
}

// 保存为草稿
const handleSaveDraft = async () => {
  // 验证必填项
  if (!formData.inventoryTypeId) {
    ElMessage.warning('请选择盘点类型')
    return
  }
  if (!formData.startTime) {
    ElMessage.warning('请选择盘点开始时间')
    return
  }
  if (!formData.endTime) {
    ElMessage.warning('请选择盘点结束时间')
    return
  }

  // 验证时间范围
  if (!validateTimeRange()) {
    return
  }

  if (!formData.warehouse) {
    ElMessage.warning('请选择仓库')
    return
  }
  if (!formData.operator) {
    ElMessage.warning('请选择经办人')
    return
  }
  if (items.value.length === 0) {
    ElMessage.warning('请至少添加一个盘点明细')
    return
  }

  try {
    // 构建盘点明细列表
    const detailsList = items.value.map((item: any) => ({
      inventory_check_detailsId: item.inventoryCheckDetailsId || 0,
      inventoryCode: formData.code,
      detailsProductName: item.name || item.productName || '',
      detailsProductCode: item.code || item.productCode || '',
      specificationModel: item.spec || item.specificationModel || '',
      detailsUnit: item.unit || '',
      bookStock: String(item.bookStock || item.currentInventory || ''),
      bookAmount: String(item.bookAmount || ''),
      countedStock: Number(item.inventoryQuantity) || 0,
      countedStockLocation: String(item.inventoryLocation || ''),  // 转换为字符串
      countedStockRaw: String(item.inventoryQuantity || ''),
      countedStockNumeric: String(item.inventoryQuantity || ''),
      profitLossQty: String(item.difference || ''),
      profitLossAmount: String(item.profitLossAmount || ''),
      status: item.status === '盘盈' ? 1 : item.status === '盘亏' ? 2 : 0,
      referencePrice: String(item.referencePrice || ''),
      remark: item.remark || ''
    }))

    // 构建附件列表
    const attachmentList = fileList.value.map((file: UploadFile) => ({
      uploadId: (file as any).raw?.uploadId || 0,
      inventoryCode: formData.code,
      uploadUrl: file.url || file.name
    }))

    // 验证经办人ID
    const handlerrId = Number(formData.operator)
    console.log('验证经办人ID:', {
      原始值: formData.operator,
      转换后: handlerrId,
      类型: typeof handlerrId,
      是否有效: !isNaN(handlerrId) && handlerrId > 0
    })

    if (isNaN(handlerrId) || handlerrId === 0) {
      ElMessage.error('经办人ID无效,请重新选择经办人')
      return
    }

    // 构建请求参数
    const params = {
      inventoryDTO: {
        inventoryId: isEditMode.value ? currentInventoryId.value : 0,
        inventoryCode: formData.code,
        warehouseId: Number(formData.warehouse),
        handlerrId: handlerrId,
        inventoryTypeId: formData.inventoryTypeId,
        inventoryDateTime: formData.startTime,
        inventoryEndTime: formData.endTime,
        inventoryContent: formData.remark || '',
        inventoryQuantity: String(summaryData.value.inventoryQtyTotal),
        surplusQuantity: String(summaryData.value.profitCount),
        inventoryShortageQuantity: String(summaryData.value.lossCount),
        surplusAmount: String(summaryData.value.profitAmount),
        inventoryLossAmount: String(summaryData.value.lossAmount),
        dataStatus: 1, // 保存为草稿
        detailsList: detailsList,
        attachmentList: attachmentList,
        operatorName: selectedHandlerName.value
      },
      command: 'SaveInventoryDraft'  // 保存草稿命令
    }

    console.log('保存草稿参数:', params)
    console.log('完整JSON:', JSON.stringify(params, null, 2))

    const response: any = await SaveInventory(params)

    if (response.code === 400) {
      ElMessage.success('保存草稿成功')
      // 清空表单数据和盘点明细
      resetFormData()
      // 跳转到库存显示页面
      router.push('/warehouse/inventory')
    } else {
      ElMessage.error(response.message || '保存草稿失败')
    }
  } catch (error: any) {
    console.error('保存草稿失败:', error)
    ElMessage.error(error.message || '保存草稿失败')
  }
}

// 保存
const handleSave = async () => {
  // 验证必填项
  if (!formData.inventoryTypeId) {
    ElMessage.warning('请选择盘点类型')
    return
  }
  if (!formData.startTime) {
    ElMessage.warning('请选择盘点开始时间')
    return
  }
  if (!formData.endTime) {
    ElMessage.warning('请选择盘点结束时间')
    return
  }

  // 验证时间范围
  if (!validateTimeRange()) {
    return
  }

  if (!formData.warehouse) {
    ElMessage.warning('请选择仓库')
    return
  }
  if (!formData.operator) {
    ElMessage.warning('请选择经办人')
    return
  }
  if (items.value.length === 0) {
    ElMessage.warning('请至少添加一个盘点明细')
    return
  }

  try {
    // 构建盘点明细列表
    const detailsList = items.value.map((item: any) => ({
      inventory_check_detailsId: item.inventoryCheckDetailsId || 0,
      inventoryCode: formData.code,
      detailsProductName: item.name || item.productName || '',
      detailsProductCode: item.code || item.productCode || '',
      specificationModel: item.spec || item.specificationModel || '',
      detailsUnit: item.unit || '',
      bookStock: String(item.bookStock || item.currentInventory || ''),
      bookAmount: String(item.bookAmount || ''),
      countedStock: Number(item.inventoryQuantity) || 0,
      countedStockLocation: String(item.inventoryLocation || ''),  // 转换为字符串
      countedStockRaw: String(item.inventoryQuantity || ''),
      countedStockNumeric: String(item.inventoryQuantity || ''),
      profitLossQty: String(item.difference || ''),
      profitLossAmount: String(item.profitLossAmount || ''),
      status: item.status === '盘盈' ? 1 : item.status === '盘亏' ? 2 : 0,
      referencePrice: String(item.referencePrice || ''),
      remark: item.remark || ''
    }))

    // 构建附件列表
    const attachmentList = fileList.value.map((file: UploadFile) => ({
      uploadId: (file as any).raw?.uploadId || 0,
      inventoryCode: formData.code,
      uploadUrl: file.url || file.name
    }))

    // 验证经办人ID
    const handlerrId = Number(formData.operator)
    console.log('验证经办人ID:', {
      原始值: formData.operator,
      转换后: handlerrId,
      类型: typeof handlerrId,
      是否有效: !isNaN(handlerrId) && handlerrId > 0
    })

    if (isNaN(handlerrId) || handlerrId === 0) {
      ElMessage.error('经办人ID无效,请重新选择经办人')
      return
    }

    // 构建请求参数
    const params = {
      inventoryDTO: {
        inventoryId: isEditMode.value ? currentInventoryId.value : 0,
        inventoryCode: formData.code,
        warehouseId: Number(formData.warehouse),
        handlerrId: handlerrId,
        inventoryDateTime: formData.startTime,
        inventoryEndTime: formData.endTime,
        inventoryTypeId: formData.inventoryTypeId,
        inventoryContent: formData.remark || '',
        inventoryQuantity: String(summaryData.value.inventoryQtyTotal),
        surplusQuantity: String(summaryData.value.profitCount),
        inventoryShortageQuantity: String(summaryData.value.lossCount),
        surplusAmount: String(summaryData.value.profitAmount),
        inventoryLossAmount: String(summaryData.value.lossAmount),
        dataStatus: 2, // 保存
        detailsList: detailsList,
        attachmentList: attachmentList,
        operatorName: selectedHandlerName.value
      },
      command: 'SaveInventory'  // 保存命令
    }

    console.log('保存参数:', params)
    console.log('完整JSON:', JSON.stringify(params, null, 2))

    const response: any = await SaveInventory(params)

    if (response.code === 400) {
      ElMessage.success('保存成功')
      // 清空表单数据和盘点明细
      resetFormData()
      // 跳转到库存显示页面
      router.push('/warehouse/inventory')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  }
}
</script>

<style scoped>
.inventory-add-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-card {
  margin-bottom: 0;
}

.section-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.add-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

.add-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.input-with-action {
  display: flex;
  align-items: center;
  width: 100%;
}

.selected-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

/* 经办人选择对话框样式 */
.handler-dialog-content {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
  min-height: 460px;
}

.dialog-left,
.dialog-center,
.dialog-right {
  display: flex;
  flex-direction: column;
}

.dialog-left {
  border-right: 1px solid #ebeef5;
  padding-right: 16px;
}

.dialog-center {
  border-right: 1px solid #ebeef5;
  padding-right: 16px;
}

.dialog-right {
  padding-left: 0;
}

.handler-list {
  padding: 8px;
}

.handler-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
  user-select: none;
  margin-bottom: 4px;
}

.handler-item:hover {
  background-color: #f5f7fa;
}

.handler-item.is-selected {
  background-color: #f0f9ff;
  color: #409eff;
  font-weight: 500;
}

.selected-header {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  padding: 8px 0;
}

.selected-list {
  padding: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 货品选择对话框样式 */
.product-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 24px;
  margin-right: 0;
}

.product-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.product-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.product-dialog :deep(.el-dialog__footer) {
  padding: 0;
  border-top: 1px solid #e4e7ed;
}

/* 搜索容器 */
.product-search-container {
  padding: 16px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
}

.search-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}

.product-search-bar {
  background: white;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.search-form :deep(.el-input__prefix) {
  color: #909399;
}

/* 已选择提示 */
.selected-tip {
  padding: 10px 20px;
  background-color: #f0f9ff;
  border-top: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}

/* 表格容器 */
.product-table-container {
  padding: 16px 20px;
}

.product-table-container :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.product-table-container :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.product-table-container :deep(.el-table__body tr:hover) {
  background-color: #f5f7fa;
}

.product-table-container :deep(.el-table__row) {
  transition: all 0.3s ease;
}

/* 分页样式 */
.product-pagination {
  padding: 12px 20px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fafafa;
  border-top: 1px solid #e4e7ed;
}

.pagination-info {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.pagination-info strong {
  margin: 0 4px;
  font-size: 16px;
}

.product-pagination :deep(.el-pagination) {
  padding: 0;
}

.product-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
}

/* 底部操作栏 */
.product-dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  background: linear-gradient(180deg, #f5f7fa 0%, #ffffff 100%);
}

.footer-info {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.footer-actions {
  display: flex;
  gap: 10px;
}

.footer-actions :deep(.el-button) {
  padding: 10px 20px;
  font-weight: 500;
}

.footer-actions :deep(.el-button--primary:not(:disabled)) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.footer-actions :deep(.el-button--primary:not(:disabled):hover) {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  transform: translateY(-1px);
}

.footer-actions :deep(.el-button--primary:disabled) {
  background: #c0c4cc;
  border-color: #c0c4cc;
  cursor: not-allowed;
}

.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

/* 表格容器滚动样式 */
.table-container {
  width: 100%;
  max-height: 550px;
  overflow-x: auto;
  overflow-y: auto;
}

/* 横向滚动条样式 */
.table-container::-webkit-scrollbar {
  height: 8px;
  width: 8px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Element Plus 表格内部滚动条样式 */
.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 自定义合计行样式 */
.custom-summary-row {
  background-color: #f5f5f5;
  border: 1px solid #dcdfe6;
  border-top: 2px solid #409eff;
  border-radius: 4px;
  padding: 15px 20px;
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-wrap: wrap;
  gap: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.summary-label {
  font-size: 14px;
  font-weight: 700;
  color: #303133;
  margin-right: auto;
  padding-right: 20px;
}

.summary-item {
  font-size: 13px;
  color: #606266;
  margin-right: 15px;
  white-space: nowrap;
}

.summary-item strong {
  font-weight: 700;
  color: #ff9800;
  margin-left: 4px;
}

/* 复合单位编辑对话框样式 */
.composite-unit-dialog :deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.composite-unit-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.composite-unit-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.composite-unit-dialog :deep(.el-table) {
  font-size: 13px;
}

.composite-unit-dialog :deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #606266;
}

.composite-unit-dialog :deep(.el-table td) {
  padding: 12px 0;
}

/* 上传附件样式 */
.upload-container {
  width: 100%;
}

.upload-dragger {
  text-align: center;
  padding: 40px 20px;
}

.upload-icon {
  font-size: 67px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
  cursor: pointer;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.upload-container :deep(.el-upload-dragger) {
  width: 100%;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.upload-container :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.upload-container :deep(.el-upload-list) {
  margin-top: 16px;
}

.upload-container :deep(.el-upload-list__item) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.upload-container :deep(.el-upload-list__item:hover) {
  background-color: #f5f7fa;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
  position: sticky;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: 10;
}
</style>
